import { showToast, navigateBack } from "@tarojs/taro";
import Navbar from "@/components/Navbar";
import authStore from "@/stores/AuthStore";
import {
  Button,
  DatePicker,
  Form,
  Input,
  Uploader,
  PickerOption,
  Radio,
} from "@nutui/nutui-react-taro";
import { observer } from "mobx-react-lite";
import { useCallback, useState } from "react";
import ImageConstant from "@/constant/ImageConstant";
import CodeConstant from "@/constant/CodeConstant";
import "./index.less";
import useIdentity from "@/hooks/useIdentity";
import userStore from "@/stores/UserStore";
import systemStore from "@/stores/SystemStore";
import EmptyComp from "@/components/Empty";

// 选择出生日期的事件只能选到60年前
const bornStartDateYear = new Date().getFullYear() - 60;

const IdentityVerification = () => {
  const [form] = Form.useForm();
  const { userIdentityVerification } = useIdentity();
  const { token: authorization } = authStore;
  const { systemConfig } = systemStore;
  const [bornVisible, setBornVisible] = useState(false);
  const [identityBorn, setIdentityBorn] = useState<string>("1970-01-01");
  const [identityImg, setIdentityImg] = useState(["", ""]);
  const onFinish = async (value) => {
    // 验证输入的姓名
    if (value.identityName?.length < 2)
      return showToast({ title: "姓名格式不正确", icon: "none" });
    // 验证出生日期
    if (!value.identityBorn)
      return showToast({ title: "请选择出生日期", icon: "none" });
    // 验证身份证
    if (!identityImg[0])
      return showToast({ title: "请上传身份证正面照", icon: "none" });
    if (!identityImg[1])
      return showToast({ title: "请上传身份证反面照", icon: "none" });
    const cloneDeep = JSON.parse(JSON.stringify(value));
    delete cloneDeep[0];
    delete cloneDeep[1];
    delete cloneDeep.identityBorn;
    // 发送实名认证请求
    const user: any = await userIdentityVerification({
      ...cloneDeep,
      identityBorn,
      identityImg: JSON.stringify(identityImg),
    });
    userStore.setUser(user);
    await showToast({
      title: "实名成功",
      icon: "success",
    });
    navigateBack();
  };

  /**
   * 出生日期
   * @param selectedOptions
   * @param selectedValue
   */
  const onIdentityConfirm = (
    selectedOptions: PickerOption[],
    selectedValue: (string | number)[]
  ) => {
    form.setFieldsValue({
      identityBorn: selectedOptions.map((item) => item.text).join(""),
    });
    setIdentityBorn(() => selectedValue.join("-"));
  };

  /**
   * 处理身份证上传成功
   */
  const onIdentityImgSuccess = useCallback(
    (key: 0 | 1) => {
      return ({ responseText: { data } }) => {
        const res = JSON.parse(data);
        if (res.code === CodeConstant.SUCCESS) {
          setIdentityImg((pre) => {
            pre[key] = res.data;
            return [...pre];
          });
          form.setFieldsValue({
            [key + ""]: [res.data],
          });
        } else {
          showToast({
            title: res.message,
            icon: "none",
          });
        }
      };
    },
    [form]
  );

  /**
   * 展示默认图片
   */
  const getDefaultIdentityImg = (type) => {
    if (!identityImg[type]) return [];
    return [
      {
        uid: identityImg[type],
        status: "success",
        type: "image",
        url: ImageConstant.SERVER_ROOT + identityImg[type],
      },
    ];
  };

  /**
   * 处理删除事件
   */
  const onDelete = ({ uid }) => {
    setIdentityImg((pre) => {
      return pre.map((item) => {
        if (uid === item) {
          return "";
        }
        return item;
      });
    });
  };

  /**
   * 自定义上传组件
   */
  const CustomUploader = (props) => {
    const { type } = props;
    return (
      <Uploader
        url={ImageConstant.UPLOAD_IMG_VIDEO}
        maxCount={1}
        headers={{ authorization }}
        // @ts-ignore
        onSuccess={onIdentityImgSuccess(type)}
        // @ts-ignore
        defaultValue={getDefaultIdentityImg(type)}
        onDelete={onDelete}
      />
    );
  };

  return (
    <Navbar
      className="identity-verification"
      mode="back"
      title={systemConfig.verificationEntry === 1 ? "实名认证" : "NULL"}
      bgColor="var(--mini-first)"
    >
      {systemConfig.verificationEntry === 1 ? (
        <>
          <Form
            form={form}
            divider={true}
            onFinish={onFinish}
            labelPosition="left"
            footer={
              <Button nativeType="submit" block type="primary">
                完成实名
              </Button>
            }
          >
            <Form.Item
              label="姓名"
              name="identityName"
              rules={[{ required: true, message: "必填项" }]}
            >
              <Input placeholder="请输入姓名"></Input>
            </Form.Item>
            <Form.Item
              label="性别"
              name="identitySex"
              rules={[{ required: true, message: "必填项" }]}
            >
              <Radio.Group className="flex">
                <Radio value={1}>男</Radio>
                <Radio value={0}>女</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              label="民族"
              name="identityNation"
              rules={[{ required: true, message: "必填项" }]}
            >
              <Input placeholder="请输入民族"></Input>
            </Form.Item>
            <Form.Item label="出生日期" name="identityBorn">
              <Input
                placeholder="请选择出生日期"
                disabled
                onClick={() => setBornVisible(true)}
              ></Input>
            </Form.Item>
            <Form.Item
              label="住址"
              name="identityAddress"
              rules={[{ required: true, message: "必填项" }]}
            >
              <Input placeholder="请输入住址"></Input>
            </Form.Item>
            <Form.Item
              label="身份证号码"
              name="identityNumber"
              rules={[{ required: true, message: "必填项" }]}
            >
              <Input placeholder="请输入身份证号码" maxLength={18}></Input>
            </Form.Item>
            <Form.Item label="身份证正面照" name="0">
              <CustomUploader type={0} />
            </Form.Item>
            <Form.Item label="身份证反面照" name="1">
              <CustomUploader type={1} />
            </Form.Item>
          </Form>
          <DatePicker
            startDate={new Date(bornStartDateYear, 0, 1)}
            visible={bornVisible}
            showChinese
            onClose={() => setBornVisible(false)}
            onConfirm={onIdentityConfirm}
          />
        </>
      ) : (
        <EmptyComp text="暂无权限" />
      )}
    </Navbar>
  );
};
export default observer(IdentityVerification);
